<template>
    <div class="madp-product">
        <el-table
            :data="tableData"
            :header-cell-style="{
                background: 'rgb(255, 191, 191)',
                color: 'rgb(44,44,44)'
            }"
            stripe
        >
            <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
            <el-table-column prop="code" label="产品编码" align="center" width="150"></el-table-column>
            <el-table-column prop="name" label="产品名称" align="center"></el-table-column>
            <el-table-column prop="status" label="精选标识" align="center" width="120">
                <template slot-scope="scope">
                    <el-switch :disabled="scope.row.state === 2" @change="editProduct(scope.row)" v-model="scope.row.statusS" active-text inactive-text></el-switch>
                </template>
            </el-table-column>
            <el-table-column prop="onTime" label="上架日期" align="center"></el-table-column>
            <el-table-column prop="endTime" label="产品到期日期" align="center"></el-table-column>
            <el-table-column prop="type" label="产品类别" align="center" width="120">
                <template slot-scope="scope">
                    <span>{{ scope.row.type == 4 ? '贷款' : '' }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="state" label="产品状态" align="center" width="120">
                <template slot-scope="scope">
                    <span>{{ ['未发布', '已发布', '待审批', '未编辑'][scope.row.state - 1] }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button v-if="scope.row.state === 3 && permissions.cp_product_down" type="text" @click="upDownProduct(scope.row, 2)">撤销</el-button>
                    <el-button v-if="scope.row.state === 2 && permissions.cp_loan_down" type="text" @click="upDownProduct(scope.row, 1)">下架</el-button>
                    <el-button v-if="[4, 1, 0].includes(scope.row.state) && permissions.cp_loan_up" type="text" @click="upDownProduct(scope.row, 3)">上架</el-button>
                    <el-button v-if="[4, 1, 0].includes(scope.row.state) && permissions.cp_loan_edit" type="text" @click="onEdit(scope.row)">编辑</el-button>
                    <el-button v-if="[4, 1, 0].includes(scope.row.state) && permissions.cp_loan_del" type="text" @click="deleteProduct(scope.row)">删除</el-button>
                    <el-button type="text" @click="onOpen(scope.row)">查看</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            class="madp-black-pagination"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="page.current"
            :page-sizes="[5, 10, 15, 20, 30]"
            :page-size="page.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
        ></el-pagination>
        <el-dialog :close-on-click-modal="false" :title="dialogTitle" :visible.sync="showDialog" width="55%" @close="closeDialog" :before-close="beforeDialog">
            <div class="dialog-container">
                <template v-if="dialogType != 3">
                    <el-form ref="form" :model="dialogInfo" label-width="160px">
                        <el-form-item :rules="[{ required: true, message: '产品代码不能为空' }, { max: 20, min: 1, message: '产品代码20个字符' }]" label="产品编码:" prop="code" key="code">
                            <el-input v-model.trim="dialogInfo.code" placeholder="请输入产品代码" style="width: 350px" :disabled="dialogType == 1" />
                        </el-form-item>
                        <el-form-item :rules="[{ required: true, message: '产品名称不能为空' }, { max: 50, min: 1, message: '产品名称1-50个字' }]" label="产品名称:" prop="name" key="name">
                            <el-input v-model.trim="dialogInfo.name" placeholder="请输入产品名称" style="width: 350px" :disabled="dialogType == 1" />
                        </el-form-item>
                        <el-form-item label="产品到期时间:">
                            <el-date-picker
                                :disabled="dialogType == 1"
                                v-model="dialogInfo.endTime"
                                type="datetime"
                                placeholder="请选择产品到期时间"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                default-time="00:00:00"
                            ></el-date-picker>
                        </el-form-item>
                        <el-form-item :rules="[{ required: true, message: '请选择产品广告图' }]" label="产品广告图:" prop="image1">
                            <div class="show-image">
                                <div class="up-image" v-if="dialogInfo.image1">
                                    <i class="el-icon-circle-close" @click="deleteImage(1)"></i>
                                    <img :src="dialogInfo.image1" alt />
                                    <el-button type="primary" :disabled="dialogType == 1" @click="chooseImage(1)">重新上传</el-button>
                                </div>
                                <div class="add-image" v-else @click="chooseImage(1)">
                                    <i class="el-icon-plus icon-plus"></i>
                                </div>
                                <div class="image-info">
                                    <span>上传提示:</span>
                                    <span>广告图限制 </span>
                                    <span>宽:167像素</span>
                                    <span>高:124像素</span>
                                    <span>格式:bmp、jpg、png</span>
                                </div>
                            </div>
                        </el-form-item>
                        <el-form-item :rules="[{ required: true, message: '请选择内容' }]" label="添加内容" prop="loanDescType">
                            <el-select v-model="dialogInfo.loanDescType" placeholder="请选择" @change="changeLoanType" :disabled="dialogType == 1">
                                <el-option label="图文" :value="2"></el-option>
                                <el-option label="小程序" :value="1"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item v-if="dialogInfo.loanDescType == 1" :rules="[{ required: true, message: '请输入小程序原始ID' }]" label="小程序原始ID" prop="loanOrgAppId" key="loanOrgAppId">
                            <el-input v-model.trim="dialogInfo.loanOrgAppId" placeholder="请输入小程序原始ID" style="width: 350px" :disabled="dialogType == 1" />
                        </el-form-item>
                        <el-form-item v-if="dialogInfo.loanDescType == 1" :rules="[{ required: true, message: '请输入小程序AppId' }]" label="小程序AppId" prop="loanAppId" key="loanAppId">
                            <el-input v-model.trim="dialogInfo.loanAppId" placeholder="请输入小程序AppId" style="width: 350px" :disabled="dialogType == 1" />
                        </el-form-item>
                        <el-form-item v-if="dialogInfo.loanDescType == 1" :rules="[{ required: true, message: '请输入小程序入口路径' }]" label="小程序入口路径" prop="loanDescUrl" key="loanDescUrl">
                            <el-input v-model.trim="dialogInfo.loanDescUrl" placeholder="请输入小程序入口路径" style="width: 350px" :disabled="dialogType == 1" />
                        </el-form-item>
                        <el-form-item
                            v-if="dialogInfo.loanDescType == 2"
                            label="产品链接"
                            prop="url"
                            :rules="[{ pattern: /^((http|https):\/\/)+([\w\-])/, message: '请输入以http或https必须为开头的正确链接' }, { max: 300, min: 1, message: '链接长度不超过300个字符' }]"
                        >
                            <el-input v-model.trim="dialogInfo.url" placeholder="请输入产品链接" style="width: 350px" :disabled="dialogType == 1" />
                        </el-form-item>
                        <el-form-item label="产品详情图:" :rules="[dialogInfo.loanDescType == 1 ? { required: true, message: '请选择产品详情图' } : {}]" prop="image2">
                            <div class="show-image">
                                <div class="up-image" v-if="dialogInfo.image2">
                                    <i class="el-icon-circle-close" @click="deleteImage(2)"></i>
                                    <img :src="dialogInfo.image2" alt />
                                    <el-button type="primary" :disabled="dialogType == 1" @click="chooseImage(2)">重新上传</el-button>
                                </div>
                                <div class="add-image" v-else @click="chooseImage(2)">
                                    <i class="el-icon-plus icon-plus"></i>
                                </div>
                                <div class="image-info">
                                    <span>上传提示:</span>
                                    <span>广告图限制 </span>
                                    <span>大小:5M以内</span>
                                    <span>格式:bmp、jpg、png</span>
                                </div>
                            </div>
                        </el-form-item>
                        <el-form-item :rules="[{ required: true, message: '产品描述不能为空' }, { max: 20, min: 1, message: '产品描述不超过200个字符' }]" label="产品描述:" prop="desc1" key="desc1">
                            <el-input type="textarea" v-model.trim="dialogInfo.desc1" placeholder="请输入产品描述" style="width: 350px" :disabled="dialogType == 1" />
                        </el-form-item>
                        <el-form-item :rules="[{ required: true, message: '请选择可见范围' }]" label="产品可见范围:" prop="deptIds">
                            <el-button type="primary" @click="selectDepart">{{ isLook ? '查看（部门/条线）' : '请选择/编辑可见范围（部门/条线）' }}</el-button>
                        </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="showDialog = false">取 消</el-button>
                        <el-button type="primary" @click="updateProduct">确 定</el-button>
                    </span>
                </template>
                <template v-else>
                    <el-tree ref="tree" :data="departTree" show-checkbox node-key="id" :default-checked-keys="dialogInfo.deptIds" :props="defaultProps"></el-tree>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogType = oldDialogType">取 消</el-button>
                        <el-button type="primary" @click="getCheckedNodes">确 定</el-button>
                    </span>
                </template>
            </div>
        </el-dialog>
        <input type="file" ref="upfileInput" @change="uploadFile" accept="image/jpg, image/jpeg, image/png, image/gif" hidden />
    </div>
</template>
<script>
import { upload } from '@/api/customer-into/verbal-manage';
import storeApi from '@/api/store/store.js';
import { fetchTree } from '@/api/admin/dept';
import { mapGetters } from 'vuex';
export default {
    components: {},
    data() {
        return {
            blackTableLoading: false,
            tableData: [],
            page: {
                code: '',
                name: '',
                current: 1,
                size: 5,
                total: 0
            },
            productInfo: {},
            dialogInfo: {},
            showDialog: false,
            dialogTitle: '',
            dialogType: 1, // 1-产品查看 2-产品编辑 3-选择部门 4-新增产品
            isLook: false, // 当前弹窗是否为查看
            departTree: [],
            defaultProps: {
                children: 'children',
                label: 'name',
                disabled: this.isdisabledFn
            }
        };
    },
    computed: {
        ...mapGetters({
            permissions: 'permissions'
        })
    },
    watch: {
        isUpdate: function() {
            if (this.isUpdate) {
                this.getProductList();
            }
        },
        menuId: function() {
            this.page.current = 1;
            this.getProductList();
        },
        showAddLoans: function() {
            if (this.showAddLoans) {
                this.addLoanProd();
            }
        }
    },
    props: {
        isUpdate: {
            type: Boolean,
            default: false
        },
        state: {
            type: Number | String,
            default: 1 // 1-已发布 0-未发布和未编辑
        },
        menuId: {
            // 菜单id
            type: Number | String,
            default: ''
        },
        loansCode: {
            type: String,
            default: ''
        },
        loansName: {
            type: String,
            default: ''
        },
        showAddLoans: {
            type: Boolean,
            default: false
        }
    },
    created() {},
    mounted() {
        this.getProductList();
    },
    methods: {
        isdisabledFn() {
            if (this.isLook) {
                return true;
            }
            return false;
        },
        changeLoanType() {
            this.$refs.form.clearValidate(['loanOrgAppId', 'loanAppId', 'loanDescUrl', 'image2']);
        },
        chooseImage(type) {
            this.imageType = type;
            this.$refs.upfileInput.click();
        },
        // 上传文件
        uploadFile(e) {
            let files = e.target.files[0];
            if (files.size / 1024 / 1024 > 5) {
                var file = this.$refs.upfileInput;
                file.value = ''; //虽然file的value不能设为有字符的值，但是可以设置为空值
                return this.$message.warning('该图片超过5M不能上传');
            }
            let param = new FormData();
            // 将得到的文件流添加到FormData对象
            param.append('file', files);
            upload(param).then((res) => {
                let fileList = res.data.data;
                this.$set(this.dialogInfo, `image${this.imageType}`, fileList.url);
                this.$refs.form.clearValidate([`image${this.imageType}`]);
            });
            var file = this.$refs.upfileInput;
            file.value = ''; //虽然file的value不能设为有字符的值，但是可以设置为空值
        },
        deleteImage(type) {
            this.dialogInfo[`image${type}`] = '';
        },
        addLoanProd() {
            this.dialogType = 4;
            this.dialogTitle = '贷款产品新增';
            this.dialogInfo = {};
            this.dialogInfo.type = this.menuId;
            this.$set(this.dialogInfo, 'loanDescType', 2);
            this.showDialog = true;
        },
        closeDialog() {
            this.$emit('update:showAddLoans', false);
        },
        // 弹框关闭前的操作
        beforeDialog(done) {
            if (this.dialogType == 3) {
                this.dialogType = this.oldDialogType;
            } else {
                this.isLook = false;
                done();
            }
        },
        // 点击弹窗确定 更新产品数据
        updateProduct() {
            if (this.dialogType == 1) {
                return (this.showDialog = false);
            }
            this.$refs.form.validate((valid) => {
                if (!valid) return;
                if (this.dialogInfo.deptIds && this.dialogInfo.deptIds.length < 1) return this.$message.warning('请选择可见范围');
                if (this.dialogType == 4) {
                    // 新增
                    this.addProduct(this.dialogInfo);
                } else {
                    // 编辑
                    this.editProduct(this.dialogInfo, true);
                }
            });
        },
        // 获取所有选中的部门id
        getCheckedNodes() {
            if (!this.isLook) {
                let checkIds = this.$refs.tree.getCheckedKeys();
                if (checkIds.length < 1) return this.$message.warning('请选择可见范围');
                this.dialogInfo.deptIds = checkIds;
            }
            this.dialogType = this.oldDialogType;
        },
        handleSizeChange(val) {
            this.page.current = 1;
            this.page.size = val;
            this.getProductList();
        },
        handleCurrentChange(val) {
            this.page.current = val;
            this.getProductList();
        },
        // 上架/下架产品
        upDownProduct(info, type) {
            this.$confirm(`是否确定${['下架', '撤销', '上架'][type - 1]}该产品?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    if ([1, 2].includes(type)) {
                        storeApi
                            .downProduct({
                                prodId: info.id
                            })
                            .then((res) => {
                                this.$emit('update:isUpdate', true);
                                this.$message({
                                    type: 'success',
                                    message: ['下架', '撤销'][type - 1] + '成功!'
                                });
                                this.showDialog = false;
                            });
                    } else {
                        storeApi
                            .upProduct({
                                prodId: info.id
                            })
                            .then((res) => {
                                this.$emit('update:isUpdate', true);
                                this.$message({
                                    type: 'success',
                                    message: '上架成功!'
                                });
                                this.showDialog = false;
                            });
                    }
                })
                .catch(() => {});
        },
        // 删除产品
        deleteProduct(info) {
            this.$confirm(`是否确定删除该产品?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    storeApi
                        .deleteProduct({
                            prodId: info.id
                        })
                        .then((res) => {
                            this.$emit('update:isUpdate', true);
                            this.$message({
                                type: 'success',
                                message: '删除成功'
                            });
                        });
                })
                .catch(() => {});
        },
        onOpen(info) {
            this.isLook = true;
            this.dialogType = 1;
            this.dialogTitle = '产品查看';
            this.productInfo = info;
            this.showDialog = true;
            this.getProductInfo(info.id);
        },
        onEdit(info) {
            this.isLook = false;
            this.dialogType = 2;
            this.dialogTitle = '产品编辑';
            this.productInfo = info;
            this.showDialog = true;
            this.getProductInfo(info.id);
        },
        selectDepart() {
            this.oldDialogType = this.dialogType;
            this.dialogType = 3;
            this.dialogTitle = '选择可见范围';
            fetchTree().then((res) => {
                this.departTree = res.data.data;
            });
        },
        // 新增产品
        addProduct(prams) {
            storeApi.addProduct(prams).then((res) => {
                this.$message.success('新增成功');
                this.$emit('update:isUpdate', true);
                this.showDialog = false;
            });
        },
        // 获取产品信息
        getProductInfo(id) {
            storeApi
                .productInfo({
                    prodId: id
                })
                .then((res) => {
                    this.dialogInfo = res.data.data;
                    this.$set(this.dialogInfo, 'statusS', this.dialogInfo.status == 1 ? true : false);
                });
        },
        // 编辑产品
        editProduct(params, type) {
            params.status = params.statusS ? 1 : 0;
            storeApi.editProduct(params).then((res) => {
                if (type) {
                    // 弹框中尽心信息修改
                    this.$message({
                        type: 'success',
                        message: '修改成功'
                    });
                    this.productInfo = Object.assign(this.productInfo, this.dialogInfo);
                    this.showDialog = false;
                    // this.$forceUpdate()
                }
            });
        },
        // 获取产品列表
        getProductList() {
            this.blackTableLoading = true;
            storeApi
                .productList({
                    type: this.menuId,
                    current: this.page.current,
                    size: this.page.size,
                    state: this.state,
                    code: this.loansCode,
                    name: this.loansName
                })
                .then((res) => {
                    let data = res.data.data.records;
                    if (data.length == 0 && this.page.current > 1) {
                        this.page.current--;
                        this.getProductList();
                        return;
                    }
                    data.map((ele) => {
                        ele.statusS = ele.status == 1 ? true : false;
                    });
                    this.tableData = data;
                    this.page.total = res.data.data.total;
                    this.$emit('update:isUpdate', false);
                    this.blackTableLoading = false;
                })
                .catch(() => {
                    this.$emit('update:isUpdate', false);
                    this.blackTableLoading = false;
                });
        }
    }
};
</script>
<style scoped lang="scss">
.madp-black-pagination {
    text-align: right;
    margin: 20px;
}
.header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    /deep/.el-form {
        margin-left: 10px;
        align-items: center;
        display: flex;
        .el-form-item {
            display: flex;
            align-items: center;
            margin-bottom: 0;
        }
    }
}
.dialog-container {
    text-align: right;
}
/deep/.el-form-item__content {
    display: flex;
    align-items: center;
}
/deep/.el-tree-node__content {
    height: 25px !important;
}

.show-image {
    display: flex;
    flex-wrap: wrap;
    .add-image {
        width: 120px;
        height: 120px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 5px;
        border: 1px solid #eee;
        .icon-plus {
            font-size: 30px;
        }
    }
    .up-image {
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-right: 10px;
        .el-icon-circle-close {
            position: absolute;
            top: -5px;
            right: -5px;
            background: #fff;
            z-index: 97;
        }
        img {
            width: 120px;
            height: 120px;
            border: 1px solid #eee;
        }
        button {
            margin-top: 15px;
        }
    }
    .add-image:hover {
        cursor: pointer;
    }
    .image-info {
        margin-left: 10px;
        display: flex;
        flex-direction: column;
        span {
            text-align: left;
            line-height: 24px;
        }
    }
}
</style>
